package com.module.app.adapter.holder

import android.view.ViewGroup
import com.module.app.base.loadsir.EmptyCallback
import com.module.app.base.loadsir.ErrorCallback
import com.module.app.base.loadsir.LoadingCallback
import com.module.base.base.ErrorViewBean
import com.module.base.base.adapter.BaseViewHolder
import com.module.base.utils.DisplayUtils
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.module.base.databinding.ItemErrorBinding
import com.module.frame.ext.postEvent

class ErrorHolder(parent: ViewGroup) : BaseViewHolder<ErrorViewBean, ItemErrorBinding>(parent) {

    var loadService: LoadService<*>? = null

    override fun convert(bean: ErrorViewBean, position: Int) {
        loadService = LoadSir.getDefault().register(mDatabind.vError) { //执行接口请求
            if (bean.getFlowBus() != null) {
                postEvent(bean.getFlowBus()!!,true)
            }
        }
        if (adapter.recyclerView.height != 0 && itemView.top != 0) {
            setLayoutParams(bean)
        } else {
            itemView.post { setLayoutParams(bean) }
        }
    }

    private fun setLayoutParams(bean: ErrorViewBean) {
        val lp: ViewGroup.LayoutParams = mDatabind.layout.layoutParams
        val diff = adapter.recyclerView.height - itemView.top
        if (bean.isFull() && diff > DisplayUtils.dip2px(200f)) {
            lp.height = diff
        } else {
            lp.height = DisplayUtils.dip2px(200f)
        }
        mDatabind.layout.layoutParams = lp
        if (bean.getMapTransport() != null) {
            for ((key, value) in bean.getMapTransport()!!) {
                //设置缺省图样式
                loadService?.setCallBack(key, value)
            }
        }
        loadService?.showSuccess()
        when (bean.getType()) {
            ErrorViewBean.TYPE_EMPTY -> loadService?.showCallback(com.module.app.base.loadsir.EmptyCallback::class.java)
            ErrorViewBean.TYPE_ERROR -> loadService?.showCallback(com.module.app.base.loadsir.ErrorCallback::class.java)
            ErrorViewBean.TYPE_LOADDING -> loadService?.showCallback(com.module.app.base.loadsir.LoadingCallback::class.java)
            else -> loadService?.showSuccess()
        }
    }

    override fun onViewRecycled() {
        super.onViewRecycled()
        if (loadService != null) {
            loadService?.showSuccess()
            loadService = null
        }
    }
}